package com.caimiao.miao.http.retorfit;

import com.caimiao.miao.library.utils.tip.LogUtil;

import java.util.concurrent.TimeUnit;

import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * 网络框架工厂
 */
public class RetrofitFactory {
    private static volatile RetrofitFactory mInstance = null;
    private static volatile RequestApi mApi;

    private RetrofitFactory() {
    }

    public static RequestApi api() {
        if (mApi == null) {
            synchronized (RetrofitFactory.class) {
                if (mApi == null) {
                    mApi = new RetrofitFactory().request();
                }
            }
        }
        return mApi;
    }

    public static void clear() {
        mApi = null;
    }

    private OkHttpClient provideOkHttpClient() {
        OkHttpClient.Builder builder = new OkHttpClient.Builder()
                .readTimeout(HttpConfig.HTTP_CONNECT_TIMEOUT, TimeUnit.MILLISECONDS)
                .connectTimeout(HttpConfig.HTTP_CONNECT_TIMEOUT, TimeUnit.MILLISECONDS);
        if (LogUtil.canPrint) {
            HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor();
            loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
            builder = builder.addNetworkInterceptor(loggingInterceptor);
        }
        return builder.build();
    }

    public RequestApi request() {
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(HttpConfig.getBaseUrl())
                .client(provideOkHttpClient())
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .addConverterFactory(GsonConverterFactory.create())
                .build();
        return retrofit.create(RequestApi.class);
    }

}
